      /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Core;

import Core.IConnectionHandler;
import Core.IConnectionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Mr Bao
 */
public class ConnectionHandler implements IConnectionHandler {

    protected PrintWriter out;
    protected Socket socket;
    protected InputStream in;
    protected IConnectionListener connectionListener;
    protected ReaderThread reader;
    protected Dispatcher dispatcher;
    protected boolean isShutdown = false;

    public ConnectionHandler(Socket socket, IConnectionListener connectionListener) throws IOException {
        this.connectionListener = connectionListener;
        this.socket = socket;
        out = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()));
        in = this.socket.getInputStream();
    }

    public ReaderThread CreateReader() {
        return new ReaderThread(connectionListener, in, this);
    }

    public void Init() {
        reader = CreateReader();
        reader.start();
    }

    public void SetDispatcher(Dispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    public void QueueMessage(String message) {
        dispatcher.Queue(new Message(this, message));
    }

    public void SendImmediately(String message) {
        out.println(message);
        out.flush();
    }

    public synchronized void Shutdown(boolean notify) {
        if (!isShutdown) {
            isShutdown = true;
            reader.Halt();
            reader.interrupt();
            try {
                in.close();
                out.close();
                socket.close();
            } catch (Exception e) {
            }
            if (notify) {
                connectionListener.SocketClosed();
            }
        }
    }

    public void SetListener(IConnectionListener listener) {
        connectionListener = listener;
    }
}
